﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Extend
{
    /// <summary>
    /// Http请求扩展类
    /// </summary>
    public static class HttpRequestExtend
    {
        /// <summary>
        /// 判断请求是否是来自Ajax 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsAjax(this HttpRequest request)
        {
            bool result = false;

            var xreq = request.Headers.ContainsKey("x-requested-with");
            if (xreq)
            {
                result = request.Headers["x-requested-with"] == "XMLHttpRequest";
            }

            return result;
        }

        /// <summary>
        /// 是否是Api请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsApiReuest(this HttpRequest request)
        {
            try
            {
                var ContentType = request.ContentType;
                if (!ContentType.IsNullOrWhiteSpace())
                {
                    var ContentTypeLower = ContentType.ToLower();
                    var IsJson = ContentTypeLower.Contains("application/json");
                    var IsXml = ContentTypeLower.Contains("application/xml");
                    return IsJson || IsXml;
                }
                return false;
            }
            catch 
            {
                return false;
            }
        }
    }
}
